/**
 * author pcg
 */


(function($, undefined) {

    $.widget("ui.guilist", {
        values: new Array(),   //the checkedBox 's values
        buttonsBeforeSubmitcallBacks: new Array(), //customize function before toolBar's buttons click Event
        buttonsAfterSubmitcallBacks: new Array(), //customize function after toolBar's buttons click Event
        _create: function() {
            this.notifyButtons();
            this.bindRowClickEvent();
            this.bindButtonsEvent();
        },
        getCheckedRows: function () {
            var checks = new Array();
            var i = 0;
            this.element.find("div[name='guiRowChecked']").each(function() {
                if ($(this).hasClass('ui-checker-checked')) {
                    checks[i] = $(this).parent().parent();
                    i++;
                }
            });
            //alert(checks.length);
            return checks;
        },
        //button状态----由checkbox的change事件或页面初始化时触发
        notifyButtons: function() {
            var self = this;
            var hasCSS = function(cssName) {
                var checkedRows = self.getCheckedRows();
                var _css = false;
                if(checkedRows.length>1){
                    _css = true;
                } else {
                $(checkedRows).each(function() {
                    if ($(this).hasClass(cssName) && cssName != '') {//若该行有button中配置的CSS名...
                        _css = true;
                    }
                    return false;//跳出each循环
                });
                }
                return _css;
            };

            self.element.find(".ui-list-toolbar .ui-controlbar-item > a").each(function() {
//            $("input[type='button'][btnType='guiButton']").each(function() {
                var _disabled = true;
                var _css = true;
                var _requiredCSS = $(this).attr('requiredCSS');
                var _mode = $(this).attr('mode');
                if ((_mode == '1') && (self.values.length == 1)) {
                    _disabled = false;
                    if (_requiredCSS) _css = hasCSS(_requiredCSS);
                } else if ((_mode == '+') && (self.values.length >= 1)) {
                    _disabled = false;
                    if (_requiredCSS) _css = hasCSS(_requiredCSS);
                } else if ((_mode == '2') && (self.values.length == 2)) {
                    _disabled = false;
                    if (_requiredCSS) _css = hasCSS(_requiredCSS);
                } else if (_mode == '0' && (self.values.length == 0)) {
                    _disabled = false;
                    _css = false;
                } else if (_mode == '*') {
                    _disabled = false;
                    _css = true;
                } else {
                    _disabled = true;
                }
                if (_css && !_disabled) {
                    $(this).removeClass('disabled');
                } else {
                    $(this).addClass('disabled');
                }
            });
        },
        /*处理checkbox的事件及监听*/
        bindRowClickEvent: function() {
            var self = this;
            this.element.find("#guiAllRowChecked").bind("click", function() {
                if ($(this).hasClass('ui-checker-checked'))
                    $(this).removeClass('ui-checker-checked');
                else
                    $(this).addClass('ui-checker-checked');

                var nums = 0;
                var checked = self.element.find("#guiAllRowChecked").hasClass('ui-checker-checked');
                if (!checked) {
                    self.values = new Array();
                }
                self.element.find("div[name='guiRowChecked']").each(function() {
                    if (checked)
                        $(this).addClass('ui-checker-checked');
                    else
                        $(this).removeClass('ui-checker-checked');
                    if ($(this).hasClass('ui-checker-checked') && checked) {
                        self.values[nums] = $(this).attr('value');
                        nums++;
                    }
                });
                self.notifyButtons();
            });

            this.element.find("div[name='guiRowChecked']").each(function() {
                $(this).bind('click', function() {
                    if ($(this).hasClass('ui-checker-checked'))
                        $(this).removeClass('ui-checker-checked');
                    else
                        $(this).addClass('ui-checker-checked');
                    self.getCheckValues(this);
                    self.notifyButtons();
                });
            });
        },
        getCheckValues: function(checkbox) {
            var self = this;
            var _value = $(checkbox).attr('value');
            var _length = self.values.length;
            if ($(checkbox).hasClass('ui-checker-checked')) {
                if (_length == 0) {
                    self.values[0] = _value;
                } else if ($.inArray(_value, self.values) == -1) {
                    self.values[_length] = _value;
                } else {

                }
            } else {
                if ($.inArray(_value, self.values) == -1) {

                } else {
                    self.values.splice($.inArray(_value, self.values), 1);
                }
            }
        },

        getCheckedValues: function() {
            var checks = new Array();
            var i = 0;
            this.element.find("div[name='guiRowChecked']").each(function() {
                if ($(this).hasClass('ui-checker-checked')) {
                    checks[i++] = $(this).attr("value");
                }
            });
            return checks;
        },

        bindButtonsEvent: function () {
            var self = this;
            //button事件
            self.element.find(".ui-list-toolbar .ui-controlbar-item > a").each(function() {
//            $("input[type='button'][btnType='guiButton']").each(function() {
                var evts = $(this).data('events');
                if (!(evts && evts["click"])) {
                    $(this).bind('click', function(event) {
                        event.stopPropagation();
                        if ($(this).hasClass("disabled"))
                            return false;
                        var targetButton = $(this);

                        function runner() {
                            var buttonId = targetButton.attr('id');

                            //exec customize function before submit
                            var isExecSubmit = true;
                            $(self.buttonsBeforeSubmitcallBacks).each(function() {
                                var _callBack = $(this);
                                if (_callBack[0] == buttonId) {
                                    isExecSubmit = _callBack[1]();
                                }
                            });

                            if (isExecSubmit) {
                                // exec submit
                                var method = targetButton.attr('method');
                                if (method == null) {
                                    method = "GET";
                                }
                                var url = targetButton.attr('href');
                                if (targetButton.attr('batch') == true || targetButton.attr('batch') == 'true') {
                                    var executor = $.orderlyTaskExecutor.create({title:targetButton.text(),actions:[
                                        {text:l("gui_list_text_close"),handler:'window.location.reload();'}
                                    ]});
                                    $(self.values).each(function(idx) {
                                        executor.addTask({
                                                             url:self.replaceParams(url, this.replace(/\//g, '*')),
                                                             method:method,params:{seq:(idx + 1)}
                                                         });
                                    });
                                    executor.start();
                                } else if(targetButton.attr('overlay') == true || targetButton.attr('overlay') == 'true') {
                                    self.ajaxGuilist(url,self,method,"GET")
                                } else {
                                    self.locationHref(url,self,method);
                                    }
                                }
                            }

                        if (targetButton.attr('confirm')) {
                            var confireMessage = targetButton.attr('confireMessage');
                            if (!confireMessage)confireMessage = l("gui_list_text_confirm_execute");
                            $.ui.messageBox.show({title:l("gui_list_text_confirm"),msg:confireMessage,buttons:$.ui.messageBox.OKCANCEL, callback: function(result) {
                                if ($.ui.messageBox.OK[result]) {
                                    runner();
                                }
                            }});
                        }
                        else
                            runner();

                        return false;
                    });
                }
            });
        },
        addCallBackAfterSubmit: function(buttonId, callBackFun) {
            var callBack;
            $(buttonsAfterSubmitcallBacks).each(function() {
                var _callBack = $(this)
                if (_callBack[0] == buttonId) {
                    callBack = _callBack;
                }
            });
            if (!callBack) {
                callBack = new Array();
                callBack[0] = buttonId;
            }
            callBack[1] = callBackFun;
            buttonsAfterSubmitcallBacks[buttonsAfterSubmitcallBacks.length] = callBack;
        },
        addCallBackBeforeSubmit: function(buttonId, callBackFun) {
            var callBack;
            $(this.buttonsBeforeSubmitcallBacks).each(function() {
                var _callBack = $(this)
                if (_callBack[0] == buttonId) {
                    callBack = _callBack;
                }
            });
            if (!callBack) {
                callBack = new Array();
                callBack[0] = buttonId;
            }
            callBack[1] = callBackFun;
            this.buttonsBeforeSubmitcallBacks[this.buttonsBeforeSubmitcallBacks.length] = callBack;
        },

        replaceParams: function(url, id) {
            //var reg = /\:(.*?)\//g;
            var reg = /:key/gi;
            var params = url.match(reg);
            if (params.length == 1) {
                url = url.replace(/:key/g, id);
            } else {
                for (var i = 0; i < params.length; i++) {
                    var paramValue = this.element.find("#" + id + "_" + i).attr("value");
                    url = url.replace(params[i], paramValue);
                }
            }
            url = encodeURI(url);
            return url;
        },

        locationHref: function(url,self,method){
            var replacedUrl = url.replace(/:key/g, self.values.join());
            if(method && method != "GET"){
                if (replacedUrl.indexOf("?") > 0)
                    replacedUrl += "&_method=" + method;
                else
                    replacedUrl += "?_method=" + method;
        }
            replacedUrl= encodeURI(replacedUrl);
            window.location.href = replacedUrl;
        },

        ajaxGuilist: function(url, self,method,type) {
            $.ajax({
                   type: type,
                   timeout: 600000,
                   url: encodeURI(url.replace(/:key/g, self.values.join())),
                   cache: false,
                   complete: function(response) {
                       if(response.status == 500||response.status == 400) {
                            miniOverLay(l("gui_list_text_tips"));
                            var msg = "<br/>" + response.responseText.toString();
                            $("body").data("dialog").append(msg);
                            $("body").data("dialog").addButton({text:l("gui_list_text_confirm"),handler:'location.href = location.href'});
                            $("body").data("dialog").addButton({text:l("gui_list_text_close")});
                           if (waiting) {
                               $("#task-startTip").remove();
                           }
                       } else if(response.status == 200) {
                            self.locationHref(url,self,method);
                       }
                   }
    });
        }

    });

    $.extend($.ui.guilist, {
        version: "1.8.15"
    });


}(jQuery));


